package com.kaiwukj.android.ufamily.hx;

import android.util.Log;

import androidx.annotation.NonNull;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPUtils;
import com.google.gson.Gson;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.easeui.domain.EaseUser;
import com.j256.ormlite.dao.Dao;
import com.kaiwukj.android.ufamily.app.MyApplication;
import com.kaiwukj.android.ufamily.app.constant.SPParam;
import com.kaiwukj.android.ufamily.mvp.http.api.service.AccountService;
import com.kaiwukj.android.ufamily.mvp.http.callback.ApiCallBack;
import com.kaiwukj.android.ufamily.mvp.http.entity.result.UserSimpleResult;
import com.kaiwukj.android.ufamily.mvp.http.utils.RxUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户缓存管理类
 * Created by Martin on 2017/4/24.
 */
public class UserCacheManager {
    /**
     * 消息扩展属性
     */
    private static final String kChatUserId = "userId";// 当前用户hxID
    private static final String kChatUserNick = "nickName";// 昵称
    private static final String kChatUserPic = "avatar";// 头像Url
    private static final String kChatHXId = "huanxinId";//当前用户Id
    private static final String kIsButler = "isButler";//1-t 0-f  是否是管家

    /**
     * 获取所有用户信息
     *
     * @return
     */
    public static List<UserCacheInfo> getAll() {
        Dao<UserCacheInfo, Integer> dao = SqliteHelper.getInstance().getUserDao();
        try {
            List<UserCacheInfo> list = dao.queryForAll();
            return list;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 获取用户信息
     *
     * @param userId 用户环信ID
     * @return
     */
    public static UserCacheInfo get(final String userId) {
        UserCacheInfo info = null;


        // 如果本地缓存不存在或者过期，则从存储服务器获取
        if (notExistedOrExpired(userId) && !isKeeper(userId)) {
            MyApplication.getInstance().getAppComponent()
                    .repositoryManager().obtainRetrofitService(AccountService.class)
                    .getUserByHxName(userId)
                    .compose(RxUtils.handleResult())
                    .compose(RxUtils.schedulerHelper())
                    .subscribe(new ApiCallBack<UserSimpleResult>() {
                        @Override
                        public void onSuccess(@NonNull UserSimpleResult result) {
                            LogUtils.e("result---------------->" + GsonUtils.toJson(result));
                            save(result.getUserId(), userId, result.getNickName(), result.getHeadImg());
                            // info = getFromCache(String.valueOf(result.getId()));
                        }
                    });
        }
        info = getFromCache(userId);

        return info;
    }

    /**
     * 获取用户信息
     *
     * @param userId 用户环信ID
     * @return
     */
    public static UserCacheInfo getFromCache(String userId) {
        try {
            Dao<UserCacheInfo, Integer> dao = SqliteHelper.getInstance().getUserDao();
            UserCacheInfo model = dao.queryBuilder().where().eq("userId", userId).queryForFirst();
            return model;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 获取用户信息
     *
     * @param userId
     * @return
     */
    public static EaseUser getEaseUser(String userId) {
        UserCacheInfo user = get(userId);
        if (user == null) return null;
        EaseUser easeUser = new EaseUser(userId);
        easeUser.setAvatar(user.getAvatarUrl());
        easeUser.setNickname(user.getNickName());
        return easeUser;
    }

    /**
     * 用户是否存在
     *
     * @param userId 用户环信ID
     * @return
     */
    public static boolean isExisted(String userId) {
        Dao<UserCacheInfo, Integer> dao = SqliteHelper.getInstance().getUserDao();
        try {
            long count = dao.queryBuilder().where().eq("userId", userId).countOf();
            return count > 0;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return false;
    }

    /**
     * 用户不存在或已过期
     *
     * @param userId 用户环信ID
     * @return
     */
    public static boolean notExistedOrExpired(String userId) {
        Dao<UserCacheInfo, Integer> dao = SqliteHelper.getInstance().getUserDao();
        try {
            long count = dao.queryBuilder().where()
                    .eq("userId", userId).and()
                    .gt("expiredDate", new Date().getTime())
                    .countOf();
            return count <= 0;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return true;
    }

    /**
     * 缓存用户信息
     *
     * @param userId    用户环信ID
     * @param avatarUrl 头像Url
     * @param nickName  昵称
     * @return
     */
    @Deprecated
    public static boolean save(String userId, String nickName, String avatarUrl) {
        try {
            Dao<UserCacheInfo, Integer> dao = SqliteHelper.getInstance().getUserDao();

            UserCacheInfo user = getFromCache(userId);

            // 新增
            if (user == null) {
                user = new UserCacheInfo();
            }

            user.setUserId(userId);
            user.setAvatarUrl(avatarUrl);
            user.setNickName(nickName);
            user.setExpiredDate(new Date().getTime() + 24 * 60 * 60 * 1000);// 一天过期，单位：毫秒

            Dao.CreateOrUpdateStatus status = dao.createOrUpdate(user);
            if (status.getNumLinesChanged() > 0) {
                Log.i("UserCacheManager", "操作成功~");
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("UserCacheManager", "操作异常~");
        }

        return false;
    }

    /**
     * 缓存用户信息
     *
     * @param uId       用户ID
     * @param hxId      用户环信ID
     * @param avatarUrl 头像Url
     * @param nickName  昵称
     * @return
     */
    public synchronized static boolean save(int uId, String hxId, String nickName, String avatarUrl) {
        try {
            Dao<UserCacheInfo, Integer> dao = SqliteHelper.getInstance().getUserDao();

            UserCacheInfo user = getFromCache(hxId);

            // 新增
            if (user == null) {
                user = new UserCacheInfo();
            }

            user.setuId(uId);
            user.setUserId(hxId);
            user.setAvatarUrl(avatarUrl);
            user.setNickName(nickName);
            user.setExpiredDate(new Date().getTime() + 24 * 60 * 60 * 1000);// 一天过期，单位：毫秒

            Dao.CreateOrUpdateStatus status = dao.createOrUpdate(user);
            LogUtils.d("status------------------->" + GsonUtils.toJson(status));
            if (status.getNumLinesChanged() > 0) {
                LogUtils.i("--------------操作成功~--------------");
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
            LogUtils.e("--------------操作异常~");
        }

        return false;
    }


    /**
     * 缓存用户信息
     *
     * @param model 用户信息
     * @return
     */
    public static boolean save(UserCacheInfo model) {

        if (model == null) return false;

        return save(model.getuId(), model.getUserId(), model.getNickName(), model.getAvatarUrl());
    }

    /**
     * 缓存用户信息
     *
     * @param ext 用户信息
     * @return
     */
    public static boolean save(String ext) {
        if (ext == null) return false;

        UserCacheInfo user = UserCacheInfo.parse(ext);
        return save(user);
    }

    /**
     * 缓存用户信息
     *
     * @param ext 消息的扩展属性
     * @return
     */
    public static void save(Map<String, Object> ext) {

        if (ext == null) return;

        LogUtils.d("ext--------------------------->" + GsonUtils.toJson(ext));

        try {

            boolean isKeeper = false;
            Object isButler = ext.get(kIsButler);
            if (isButler instanceof Integer) {
                if ((int) isButler == 1) {
                    isKeeper = true;
                }
            }

            Integer uId = (Integer) ext.get(kChatUserId);

            // int uId = (int) ext.get(kChatUserId);
            String userId = (String) ext.get(kChatHXId);
            String avatarUrl = (String) ext.get(kChatUserPic);
            String nickName = (String) ext.get(kChatUserNick);

            save(isKeeper ? -1 : uId == null ? -1 : uId, userId == null ? "" : userId, nickName == null ? "" : nickName, avatarUrl == null ? "" : avatarUrl);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取当前环信用户信息
     *
     * @return
     */
    public static UserCacheInfo getMyInfo() {
        return get(EMClient.getInstance().getCurrentUser());
    }

    /**
     * 获取用户昵称
     *
     * @return
     */
    public static String getMyNickName() {
        UserCacheInfo user = getMyInfo();
        if (user == null) return EMClient.getInstance().getCurrentUser();

        return user.getNickName();
    }

    public static boolean isKeeper(String conversationId) {
        boolean isKeeper = false;
        EMConversation conversation = EMClient.getInstance().chatManager().getConversation(conversationId);
        if (conversation != null) {
            EMMessage message = conversation.getLatestMessageFromOthers();
            if (message != null) {
                isKeeper = isKeeper(message.ext());
            }
        }
        return isKeeper;
    }

    public static boolean isKeeper(Map<String, Object> ext) {
        boolean flag = false;
        if (ext != null) {
            try {
                Integer keeper = (Integer) ext.get(kIsButler);
                if (keeper != null && keeper == 1) {
                    flag = true;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return flag;
    }

    /**
     * 设置消息的扩展属性
     *
     * @param msg 发送的消息
     */
    public static void setMsgExt(EMMessage msg) {
        if (msg == null) return;

        UserCacheInfo user = getMyInfo();
        if (user != null) {
            msg.setAttribute(kChatUserId, user.getuId());
            msg.setAttribute(kChatHXId, user.getUserId());
            msg.setAttribute(kChatUserNick, user.getNickName());
            msg.setAttribute(kChatUserPic, user.getAvatarUrl());
        } else {
            msg.setAttribute(kChatHXId, SPUtils.getInstance().getString(SPParam.HX_USER_ID));
            msg.setAttribute(kChatUserNick, SPUtils.getInstance().getString(SPParam.HX_USER_NICK_NAME));
            msg.setAttribute(kChatUserPic, SPUtils.getInstance().getString(SPParam.HX_HEAD_IMAGE));
            msg.setAttribute(kChatUserId, SPUtils.getInstance().getString(SPParam.USER_ID));
        }


    }

    /**
     * 获取登录用户的昵称头像
     *
     * @return
     */
    public static String getMyInfoStr() {
        Map<String, Object> map = new HashMap<>();
        UserCacheInfo user = getMyInfo();
        map.put(kChatHXId, user.getUserId());
        map.put(kChatUserId, user.getuId());
        map.put(kChatUserNick, user.getNickName());
        map.put(kChatUserPic, user.getAvatarUrl());
        return new Gson().toJson(map);
    }
}
